<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('头程装箱单-分箱')" />
	<th:block th:include="include :: businessCSS" />
	<style>
        .main-content{position: relative;}
        .topbtns{position:fixed;top: 0;width: 100%;z-index: 9999;background-color: #fff;}
		.preservationBtn{padding: 10px;margin: 0;position: fixed;top: 0;z-index: 9999;background: #fff;width: 100%;}
		.preservationBtn input{font-size: 16px;background-color: rgb(80, 138, 238);color: #fff;border: none;padding: 5px 30px;border-radius: 5px;cursor: pointer;}
		.layui-table-tool-temp{padding-right: 30px;}
        .getDetailUpload,.getDetailUpload2{cursor: pointer;}
        .layui-table-tool-self{display: none;}
		.tablebody{background-color: #fff;padding: 20px;margin-right: 15px;}
		.tablebody input{display: inline;width: 80%;border: none;}
		.tablebody table{width: 100%;}
		.tablebody th,.tablebody td{border:solid 1px #ddd;padding:10px;font-size:14px;text-align: center;}
		.redcolor{color: red;cursor: pointer;min-width: 40px;}
		.bluecolor{color: rgb(71, 150, 253);cursor: pointer;min-width: 50px;}
	</style>
</head>
<body class="no-skin">
<div class="main-container" id="main-container">
	<div class="main-content">
	<form class="layui-form head-form">
	    <div class="north" style="background-color: #fff;margin-top: 55px;">
			 <div class="layui-form-item preservationBtn">
                <button class="layui-btn layui-btn-normal dhicon btn-edit" type="button" lay-submit lay-filter="btn-edit" id="btn-edit">分箱</button>
			</div>
			<div class="forminput"></div>
    	</div>
        <div style="width: 100%;height: 10px;background: #f6f6f6;"></div>
        <div>
            <table class="layui-hide" id="mjdhtable" lay-filter="mjtable"></table>
            <script type="text/html" id="zjtoolbar">
                <div style="padding: 16px;display: flex;justify-content: space-between;">
                    <div  style="font-weight: 700;font-size: 18px;">海外头程装箱清单</div>
            	</div>
            </script>
        </div>
		<div style="width: 100%;height: 10px;background: #f6f6f6;"></div>
		<div class="tablebody" style="background-color: #fff;margin-top: 20px; height:550px;">
			<table class="fxtable layui-table " id="fxdhtable" lay-filter="fxtable">
				<div style="padding: 16px;display: flex;justify-content: space-between;">
					<div  style="font-weight: 700;font-size: 18px;">分箱清单</div>
					<div>
						<button type="button" class="layui-btn layui-btn-normal" onclick="binning(-1)">添加箱子数据</button>
					</div>
				</div>
				<thead>
				<tr>
					<th></th>
					<th>单号</th>
					<th>原箱号</th><th>箱重(kg)</th>
					<th>箱规长(cm)</th><th>箱规宽(cm)</th>
					<th>箱规高(cm)</th><th>抛重(kg)</th>
					<th>单箱采购总价(￥)</th>
					<th>操作</th>
				</tr>
				</thead>
				<tbody class="tbody1"><tr><td colspan="11">暂无数据</td></tr></tbody>
				<tbody class="tbody"></tbody>
			</table>
		</div>
        <th:block th:include="include :: pageFooter" />
    </form>
	</div>
</div>

<th:block th:include="include :: footer" />
<th:block th:include="include :: businessJS" />
<th:block th:include="include :: inlineJS" />


<script th:inline="javascript">
	/*<![CDATA[*/
	var fields = [[${fields}]];
    var fieldsList = [[${fieldsList}]];
	var fieldsHiddenList = [[${fieldsHiddenList}]];
	var moduleTable = [[${moduleTable}]];
	var enableEdit = [[${enableEdit}]];
    var List=[[${List}]];
    var binningList=[[${binningList}]];
	var listData1=List ?List:[]
	//表头数据
	var headData=[[${headData}]];
    var tablecols=[[ //标题栏
		{align: 'center', title: '商品信息', colspan: 14,width: 100}
		,{align: 'center', title: '装箱情况', colspan: 13,width: 100}
	], [
		{align: 'center',field: 'serial', title: '操作', width: 100}
        ,{align: 'center',field: 'commodityCode', title: '商品编码', width: 100}
        ,{align: 'center',field: 'nameGoodsCn', title: '商品名称', width: 100}
		,{align: 'center',field: 'nameGoodsCn', title: '商品品名(中文)', width: 100}
		,{align: 'center',field: 'codeGoodsHs', title: '海关编码', width: 100}
		,{align: 'center',field: 'nameMaterialCn', title: '商品材质(中文)', width: 100}
        ,{align: 'center',field: 'priceIn', title: '商品采购价（¥）', width: 100}
        ,{align: 'center',field: 'linkJP', title: '竞品链接', width: 100}
        ,{align: 'center',field: 'vDFilesDefault', title: '是否有附件', width: 100,hide: true}
        ,{align: 'center',field: 'spGuid', title: '商品id', width: 100,hide: true}
		,{align: 'center',field: 'sku', title: 'SKU', width: 110}
		,{align: 'center',field: 'asin', title: 'ASIN', width: 110}
		,{align: 'center',field: 'fnsku', title: 'FNSKU', width: 110}
		,{align: 'center',field: 'numPlanDeliver', title: '计划发货数量', width: 100}
		,{align: 'center',field: 'numRealityDeliver', title: '实际发货数量', width: 100,hide: true}
		,{align: 'center',field: 'numRealityDeliver1', title: '第一箱', width: 95,edit:'text'}
		,{align: 'center',field: 'numRealityDeliver2', title: '第二箱', width: 95,edit:'text'}
		,{align: 'center',field: 'numRealityDeliver3', title: '第三箱', width: 95,edit:'text'}
		,{align: 'center',field: 'numRealityDeliver4', title: '第四箱', width: 95,edit:'text'}
		,{align: 'center',field: 'numRealityDeliver5', title: '第五箱', width: 95,edit:'text'}
		,{align: 'center',field: 'numRealityDeliver6', title: '第六箱', width: 95,edit:'text'}
		,{align: 'center',field: 'numRealityDeliver7', title: '第七箱', width: 95,edit:'text'}
		,{align: 'center',field: 'numRealityDeliver8', title: '第八箱', width: 95,edit:'text'}
		,{align: 'center',field: 'numRealityDeliver9', title: '第九箱', width: 95,edit:'text'}
		,{align: 'center',field: 'numRealityDeliver10', title: '第十箱', width: 95,edit:'text'}
	]]


	var $,layer,form,table,nid,noTable;
    layui.use(['laydate','form','layer','jquery','util','element','upload','table'], function () {
        $ = layui.$,layer = layui.layer,form = layui.form,laydate = layui.laydate,util = layui.util,element=layui.element,upload = layui.upload,table = layui.table;
        beforeInit();//表单初始化之前的动作集合
		//初始化操作
		headcom3()
        nid=$('#nid').val()
         // 保存按钮事件变化
        $(function(){
           $('.tp-save').attr('onclick','')
           $('.tp-save').attr('lay-filter','btn-edit')
           $('.tp-save').attr('lay-submit',true)
        })

		//移除表格编辑属性
		$.each(tablecols[1],function(i,v){delete v['edit']});

        
        // 保存操作
        form.on('submit(btn-edit)', function(data){
			$.modal.confirmCom('确定要分箱么？',function(result) {
				//判断是否处理了所有的箱子
				if (binningList.length != 0) return layer.msg("箱子未分配全,请核实后再操作!");
				showloadings(true);
				$.post("/logstics/fbabox/binningEditpost", {
					infoMap: JSON.stringify(data.field),
					infoItems: JSON.stringify(jsonArr)
				}, function (res) {
					if (res.code == 0) {
						// window.location.href = '/logstics/fbabox/binningEditpost?guid=' + res.data;
						layer.alert(res.msg + ",请关闭此页面", {icon: 6});
						setTimeout(function () {
							showloadings(false);
						}, 1000);
					} else {
						layer.msg(res.msg, {icon: 5});
						showloadings(false);
					}
				});
			});
		});

		// 初始化表格
        $.tablelist.init({
            elem: '#mjdhtable'
            ,data: listData1
            , page: false
            , even: true
            , limit: 10000
            , totalRow: false
            , cols: tablecols
            , toolbar: '#zjtoolbar'
            , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
            , height: '550'
            , done: function (res, curr, count) {
                listData1 = table.cache.mjdhtable;//每次重载都赋值更新表缓存
				if (headData['state'] == 1){
					$('.btn-sh').attr('disabled',true)
					$('.btn-sh').css('background',"#bbb")
					$('.btn-edit').attr('disabled',true)
					$('.btn-edit').css('background',"#bbb")
					$('.layui-col-xs4').attr("disabled",true);
					$('input').attr('disabled','disabled')
					$('input').addClass('canntEdit')
					$('.forminput').addClass('layui-disabled')
					$('.updatebtn').css('background',"#bbb")
					$('.updatebtn').attr('disabled',true)
				}
            },success:function(a,b,c){
                console.log(a,b,c)
            }
        });

        //监听单元格编辑
        table.on('edit(mjtable)', function(obj) {
		})

    });


	//第几单
	let num = 0;
	let jsonArr = [];
	//分箱操作
	function binning(value){
		binningList.sort((a,b)=>{ return a.boxIndex-b.boxIndex})//升序
		//加单
		let rows = [];
		var str = `<div class="tablebody"><table class="layui-table zjtable">
					<thead><tr>
					<th class="layui-input-block">
						<input type="checkbox" id="all" name="allIndex" lay-skin="primary" title="全选" onclick="checkAll()">
					</th>
					<th>原箱号</th><th>箱重(kg)</th>
					<th>箱规长(cm)</th><th>箱规宽(cm)</th>
					<th>箱规高(cm)</th><th>抛重(kg)</th>
					<th>单箱采购总价(￥)</th></tr>
					</thead><tbody id="tbody">`;
		$.each(binningList, function (i, v) {
			str += `<tr>`;
			str += `<td><input type="checkbox" class="chBox"  lay-skin="primary"  onclick="checkOne()"></td>`;
			str += `<td>${"第"+(v.boxIndex+1)+"箱"}</td>`;
			str += `<td>${v.weight}</td>`;
			str += `<td>${v.length}</td>`;
			str += `<td>${v.width}</td>`;
			str += `<td>${v.height}</td>`;
			str += `<td>${v.weightVol}</td>`;
			str += `<td>${v.priceSingleBoxReq}</td>`;
			str += `</tr>`;
		});
		str += `</tbody></table></div>`;
		layer.open({
			type: 1,
			area: [($(window).width() - 200)+'px', ($(window).height() - 100)+'px'],
			fix: false,//不固定
			offset: '10%',//距离顶部
			maxmin: true,//最大最小化
			shade: 0.3,//遮罩
			title: '添加箱子数据',
			content:str,
			btn: ['确定', '取消'],
			shadeClose: true,// 弹层外区域关闭
			yes: function(index, layero){
				let obj = document.getElementsByClassName("chBox");
				for (let i = 0; i < obj.length; i++) {
					if (obj[i].checked) {
						// 把获取到的值去除空白放入提前声明的数组中
						rows.push(binningList[i]);
					}
				}

				//去掉已选中数据
				binningList = binningList.filter((item) => !rows.some((ele) => ele.boxIndex === item.boxIndex));

				// 此时的 rows 数组就是所有选中的数据了
				let str2 = ``;

				let jsonObj = {
					"list" : rows,
					"num" : num,
				}
				//-1添加箱子数据 其他表格中的+操作
				if (value == -1){
					jsonArr.push(jsonObj);
				} else {
					jsonArr[value].list = jsonArr[value].list.concat(rows);
				}

				$.each(jsonArr , function (j, k) {
					$.each(k.list, function (i, v) {
						str2 += `<tr class="${v.boxIndex}">`;
						if (i == 0) {
							str2 += `<td class="redcolor" rowspan="${k.list.length}" onclick="binning(${j})">+</td>`;
							str2 += `<td rowspan="${k.list.length}">${j == 0?'原单据':'第'+(j+1)+"单"}</td>`;
						}
						str2 += `<td>${"第"+(v.boxIndex+1)+"箱"}</td>`;
						str2 += `<td>${v.weight}</td>`;
						str2 += `<td>${v.length}</td>`;
						str2 += `<td>${v.width}</td>`;
						str2 += `<td>${v.height}</td>`;
						str2 += `<td>${v.weightVol}</td>`;
						str2 += `<td>${v.priceSingleBoxReq}</td>`;
						str2 += `<td  class="bluecolor" onclick="deleteDate(${v.boxIndex})">删除</td>`
						str2 += `</tr>`;
					});
				});


				binningList=binningList.filter(i=>i!='删除')
				if (rows.length != 0){
					let tbody = document.getElementsByClassName("tbody1");
					if (tbody.length != 0) tbody[0].parentNode.removeChild(tbody[0]);
				}

				//每次+1
				num++;
				$('.tbody').html(str2)
				//关闭弹窗
				layer.close(index);
			}
		});
	}

	//全选按钮的点击事件
	function checkAll(){
		//获取id的dom元素
		let Id = document.getElementById('all');
		//获取类名为chBox的dom元素
		let chBox = document.getElementsByClassName('chBox');
		let len = chBox.length;
		for(let i=0;i<len;i++){
			//当全选按钮为true时，全部按钮都为true，否则相反
			if(Id.checked){
				chBox[i].checked=true;
			}
			else {
				chBox[i].checked=false;
			}
		}
	};

	//单个按钮的点击事件
	function checkOne(){
		let count=0;
		let chBox = document.getElementsByClassName('chBox');
		let len = chBox.length;
		for(let i=0;i<len;i++){
			//记录单选按钮为true的数量
			if(chBox[i].checked){
				count++;
			}
		}
		//当单选按钮都为true时，全选按钮也为true，否则为false
		if(count==len){
			document.getElementById('all').checked = true;
		}else {
			document.getElementById('all').checked = false;
		}
	}

	//删除数据
	function deleteDate(boxIndex) {
		//判断数据中的是否数组为空，空则删除该数据，并且回填到添加箱子数据里面，在重新渲染页面
		$.each(jsonArr , function (j, k) {
			let index = k.list.indexOf(k.list.find((e) => {return e.boxIndex=== boxIndex; }));
			if (index != -1){
				binningList.push(k.list[index]);
				k.list.splice(index,1);
			}
		});

		let jsonIndex = jsonArr.indexOf(jsonArr.find((e) => {return e.list.length === 0; }));
		if (jsonIndex != -1){
			jsonArr.splice(jsonIndex,1);
		}


		let str2 = "";
		$.each(jsonArr , function (j, k) {
			$.each(k.list, function (i, v) {
				str2 += `<tr class="${v.boxIndex}">`;
				if (i == 0) {
					str2 += `<td class="redcolor" rowspan="${k.list.length}" onclick="binning(${j})">+</td>`;
					str2 += `<td rowspan="${k.list.length}">${j == 0?'原单据':'第'+(j+1)+"单"}</td>`;
				}
				str2 += `<td>${"第"+(v.boxIndex+1)+"箱"}</td>`;
				str2 += `<td>${v.weight}</td>`;
				str2 += `<td>${v.length}</td>`;
				str2 += `<td>${v.width}</td>`;
				str2 += `<td>${v.height}</td>`;
				str2 += `<td>${v.weightVol}</td>`;
				str2 += `<td>${v.priceSingleBoxReq}</td>`;
				str2 += `<td class="bluecolor" onclick="deleteDate(${v.boxIndex})">删除</td>`
				str2 += `</tr>`;
			});
		});

		$('.tbody').html(str2)
	}
</script>

</body>
</html>